/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.common.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yami.shop.common.xss.XssWrapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

/**
 * 一些简单的安全过滤：
 * xss
 * @author lgh
 */
public class XssFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(getClass().getName());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;


        resp.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, req.getHeader(HttpHeaders.ORIGIN));
        resp.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, getHeaders(req));
        resp.addHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "7200");

        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(req.getMethod())) {
            resp.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, req.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD));
            resp.setStatus(HttpStatus.NO_CONTENT.value());

        } else {
            resp.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, req.getMethod());
            chain.doFilter(new XssWrapper(req), resp);
        }


//        logger.info("uri:{}",req.getRequestURI());
        // xss 过滤
//		chain.doFilter(new XssWrapper(req), resp);
    }

    @Override
    public void destroy() {

    }

    private String getHeaders(HttpServletRequest httpServletRequest) {
        StringBuilder params = new StringBuilder();
        String accessControlRequestHeaders = httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
        if (!(accessControlRequestHeaders == null || accessControlRequestHeaders.isEmpty())) {
            params.append(accessControlRequestHeaders).append(", ");
        }

        Enumeration<String> names = httpServletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            params.append(names.nextElement()).append(", ");
        }
        params.setLength(params.length() - ", ".length());
        return params.toString();
    }
}
